/*
 * Copyright (C) RT, 2017 by kiterunner_t
 * TO THE HAPPY FEW
 */

package com.zgys.mes.util.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.zgys.mes.util.IValuedEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;


public class ValuedEnumTypeHandler<E extends IValuedEnum> extends BaseTypeHandler<IValuedEnum> {
    private Class<E> valuedCls;


    public ValuedEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }

        this.valuedCls = type;
    }


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    IValuedEnum parameter,
                                    JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getId());
    }


    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int i = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return getValuedEnum(valuedCls, i);
        }
    }


    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int i = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return getValuedEnum(valuedCls, i);
        }
    }


    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int i = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return getValuedEnum(valuedCls, i);
        }
    }


    private static <E extends IValuedEnum> E getValuedEnum(Class<E> cls, int value) {
        E[] objs = cls.getEnumConstants();
        for (E em : objs){
            if (em.getId() == value){
                return em;
            }
        }

        return null;
    }
}

